package model {
	import model.vo.DynamicEntity;	
	
	import org.puremvc.as3.multicore.utilities.asyncstub.model.AsyncStubProxy;	
	import org.puremvc.as3.multicore.utilities.startupmanager.model.StartupResourceProxy;	
	import org.puremvc.as3.multicore.utilities.startupmanager.interfaces.IStartupProxy;	
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;	
	
	/**
	 * @author Darshan Sawardekar
	 */
	public class DynamicEntityProxy 
		extends Proxy
		implements IStartupProxy {
			
		static private var entityCount:int = 0;
		
		public var entityName:String;
		public var entitySRName:String;
		public var probabilityOfFault:Number = 0;
		public var maxDelayMSecs:Number = 1000;
		
		public function DynamicEntityProxy() {
			super(entityName = "Entity" + (++entityCount));
			
			entitySRName = entityName + "_sr";			
		}
		
		public function load():void {
			sendLoadedNotification(loadingNotification);
			
			var asyncProxy:AsyncStubProxy = new AsyncStubProxy();
			asyncProxy.token = DynamicEntity.nextEntity();
			asyncProxy.maxDelayMSecs = maxDelayMSecs;
			asyncProxy.probabilityOfFault = probabilityOfFault;
			asyncProxy.asyncAction(loaded, failed);
		}
		
		public function get entity():DynamicEntity {
			return data as DynamicEntity;
		}
		
		override public function getProxyName():String {
			return entityName;
		}
		
		public function get loadingNotification():String {
			return entityName + "Loading";
		}
		
		public function get loadedNotification():String {
			return entityName + "Loaded";
		}
		
		public function get failedNotification():String {
			return entityName + "Failed";
		}
		
		private function loaded(result:DynamicEntity):void {
			setData(result);
			sendLoadedNotification(loadedNotification, entityName);
		}
		
		private function failed(result:DynamicEntity):void {
			sendLoadedNotification(failedNotification, entityName);
		}
		
		private function sendLoadedNotification(notificationName:String, body:Object = null):void {
			var srProxy:StartupResourceProxy = facade.retrieveProxy(entitySRName) as StartupResourceProxy;
			if (!srProxy.isTimedOut()) {
				sendNotification(notificationName, body);
			}
		}
		
	}
}
